package com.ddstation.hzsc_invs.autonomy_examination.task;

import com.alibaba.fastjson.JSONObject;
import com.ddstation.click.entity.EnforcementInfoEntity;
import com.ddstation.common.util.DateUtil;
import com.ddstation.hzsc_invs.autonomy_examination.service.DtInvsAutonomyExaminationInstitutionDataService;
import com.ddstation.hzsc_invs.autonomy_examination.service.DtInvsEnforcementDataService;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author gqw
 * @date 2020-11-25
 */
@Component
public class AutonomyExaminationTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(AutonomyExaminationTask.class);
    private static final String COMMON_URL = "http://scqwebs.bjclick.cn";
    @Inject
    private DtInvsAutonomyExaminationInstitutionDataService dtInvsAutonomyExaminationInstitutionDataService;
    @Inject
    private DtInvsEnforcementDataService dtInvsEnforcementDataService;
    /**
     * 日常自查 数据生成
     */
    public void daily(){
        //获取当前时间的  年 月 季度
        int year = Integer.parseInt(DateUtil.getCurrentYear()); //年
        int month = Integer.parseInt(DateUtil.getCurrentMonth()); //月
        int quarter = (month % 3 == 0 ? (month / 3) : (month / 3 + 1)); //季度

        //获取上个季度
        quarter--;
        if(quarter == 0){  //上个季度是否是去年
            year--;
            quarter = 4;
        }

        dtInvsAutonomyExaminationInstitutionDataService.insertData(1,year,quarter);
//        System.out.println(year+"--"+month+"---"+quarter);
    }

    /**
     * 全面自查 数据生成
     */
    public void overall(){
        int year = Integer.parseInt(DateUtil.getCurrentYear()); //年
        year -- ;//去年
        dtInvsAutonomyExaminationInstitutionDataService.insertData(0,year,null);
    }

    /**
     * 诊所是否自查 进行更新
     */
    public void data(){
        dtInvsAutonomyExaminationInstitutionDataService.updateDataDaily();
        dtInvsAutonomyExaminationInstitutionDataService.updateDataOverall();
    }


    /**
     * 执法结果中的新机构存储到  dt_invs_institution_enforcement_mapping表中
     * 并更新执法状态
     */
    public void enforcement_mapping(){
        dtInvsAutonomyExaminationInstitutionDataService.insertInstitution();
        dtInvsAutonomyExaminationInstitutionDataService.updateEnforcement();
    }

    public void getEnforcementInfo()  {
        LOGGER.info("开始获取执法结果" );
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDate = sdf.format( DateUtil.addDay(new Date(),-2));
        String secondDate = sdf.format( DateUtil.addDay(new Date(),-1));
        String result = doPost(COMMON_URL + "/Upload.asmx/getYljgCfxx", "ruCan=|"+firstDate+"|" + secondDate);
        LOGGER.info("result =>{}" , result);
        if(StringUtils.isNotEmpty(result)){
            int beginIndex = result.indexOf(">[");
            int endIndex = result.indexOf("]<");
            if (beginIndex != -1 &&  endIndex != -1 && result.length() >= (endIndex+1)) {
                result = result.substring(beginIndex+1, endIndex+1);
                List<EnforcementInfoEntity> tempList = JSONObject.parseArray(result, EnforcementInfoEntity.class);
                if(tempList.size()>0){
                    dtInvsEnforcementDataService.batchInsert(tempList);
                }
            }
        }
    }


    public String doPost(String httpUrl, String param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
//            connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes());
            // 通过连接对象获取一个输入流，向远程读取
            LOGGER.debug(String.valueOf(connection.getResponseCode()));
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 10*1024*1024);

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }

                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }

}
